package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestParams;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.ChargeActivity;
import com.eims.sls_app.dataaccess.RechargeType;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.MyAsynTaskWithProgress;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.utils.ResultChecker;
import com.eims.sls_app.view.MyToast;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONObject;

/**
 * 支付宝充值
 * 
 * @author SLS003
 */
public class RechargeActivity extends MyBaseActivity implements OnClickListener {
	private static final String TAG = "RechargeActivity";
	private Activity context = RechargeActivity.this;
	private EditText et_money;
	private Button btn_recharge;
	private ImageButton btn_back;
	private TextView tv_name;
	private double money;
	private MyAsynTask myAsynTask;

	private static final int SDK_PAY_FLAG = 1;

	private MyHandler myHandler;
	private String opt, auth, info, time, imei, crc;

	// 04-12 15:13:30.124: INFO/System.out(925):
	// 拿到订单信息：partner="2088901133614954"&seller="zhuj@sense.com.cn"&out_trade_no="1000000506"&subject="05FB1E7970C5235A2B"&body="TicketMoney"&total_fee="0.01"&notify_url="http://app.test.sls.net.cn/Home2/Room/OnlinePay/AlipayApp/Notify.aspx"&sign="QKnktGp4KSkV1FpC/rq19gzL5WxL58XNdHdyNEgyvQl+5DAzvHSAsUYtlsujjJfWxTP3FXxUu3BKQfAa3xNDcHQbnn9tr3auVtChY7lTt+Bmd7aAsJKvlpPnTrgaj5goAxvSgCBvmtt6CwPYFU3JzqYXhXOu0Ugn6ubUUn6CU4Y="

	private ProgressDialog mProgress = null;

	private TextView tvRechargeCj;// 彩金

	private RechargeType rechargeType;

	private List<ChargeActivity> typeList;

	private List<Double> doubleList;
	private DecimalFormat format = new DecimalFormat("#####0.00");
	private double Max;

	private double Min;

	private double dMoney;

	private LinearLayout linear_CJ;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			String str = (String) msg.obj;
			switch (msg.what) {

			case 0:

				linear_CJ.setVisibility(View.VISIBLE);
				tvRechargeCj.setVisibility(View.VISIBLE);
				// 0Log.e("ListSize",typeList.size()+"");
				if (typeList.size() > 0) {
					int count = typeList.size();

					for (int i = 0; i < count; i++) {

						if (rechargeType.getGiveType() == 1) {// 定比

							if ((dMoney >= typeList.get(i).getConditionLowest())
									&& (dMoney <= typeList.get(i)
											.getConditionHighest())) {

								tvRechargeCj.setText(format.format(dMoney
										* typeList.get(i).getNumerical()));
								tvRechargeCj.setTextColor(getResources()
										.getColor(R.color.red));
							}

						} else if (rechargeType.getGiveType() == 0) {// 定值

							if ((dMoney >= typeList.get(i).getConditionLowest())
									&& (dMoney <= typeList.get(i)
											.getConditionHighest())) {

								tvRechargeCj.setText(format.format(typeList
										.get(i).getNumerical()));
								tvRechargeCj.setTextColor(getResources()
										.getColor(R.color.red));
							}

						}

					}

				}

				break;

			default:
				break;
			}

		};

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_recharge);

		// // 检测安全支付服务是否被安装
		// MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(
		// RechargeActivity.this);
		// mspHelper.detectMobile_sp();
		findView();
		init();
		setListener();

		// getInitRechargeData();

	}

	private void init() {
		// DecimalFormat df = new DecimalFormat("#####0.00");
		money = 20;
		et_money.setSelection(et_money.getText().length());
		// money = Double.parseDouble(et_money.getText().toString());

		typeList = new ArrayList<ChargeActivity>();
		doubleList = new ArrayList<Double>();
	}

	/** 初始化UI */
	private void findView() {
		myHandler = new MyHandler();
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		et_money = (EditText) this.findViewById(R.id.recahge_et_money);
		btn_recharge = (Button) this.findViewById(R.id.recharge_btn_ok);
		tv_name = (TextView) this.findViewById(R.id.recahge_name2);

		tv_name.setText(App.user.getName());

		tvRechargeCj = (TextView) findViewById(R.id.tv_recharge_CJ);
		linear_CJ = (LinearLayout) findViewById(R.id.linear_CJ);

	}

	/** 绑定监听 */
	private void setListener() {
		btn_back.setOnClickListener(this);
		btn_recharge.setOnClickListener(this);
		et_money.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

				if (s.length() == 0) {

					tvRechargeCj.setVisibility(View.GONE);
					linear_CJ.setVisibility(View.GONE);

				} else {

					dMoney = Double.parseDouble(et_money.getText().toString()
							.trim());
					if (dMoney < Min) {
						Toast.makeText(context, "你所输入的金额低于活动的最小值" + Min + "元",
								Toast.LENGTH_SHORT).show();
					} else {

						handler.sendEmptyMessage(0);

					}

				}
			}
		});

	}

	private void getInitRechargeData() {

		RequestUtil requestUtil = new RequestUtil(context, false, 0) {

			@Override
			public void responseCallback(JSONObject reponseJson) {

				String StrJson = reponseJson.toString();
				Log.e(TAG, StrJson);
				if (null != reponseJson) {

					rechargeType = JSON
							.parseObject(StrJson, RechargeType.class);

					if (rechargeType.getIsSuccess().equals("true")) {

						typeList = rechargeType.getActiveList();
						if (typeList.size() != 0 && typeList != null) {

							for (int i = 0; i < typeList.size(); i++) {

								doubleList.add(typeList.get(i)
										.getConditionLowest());
								doubleList.add(typeList.get(i)
										.getConditionHighest());

							}
							Max = Collections.max(doubleList);
							Log.e("MAX", Max + "");
							Min = Collections.min(doubleList);
							Log.e("MIN", Min + "");
							Toast.makeText(context, rechargeType.getMsg(),
									Toast.LENGTH_SHORT).show();

						}
					}

				}

			}

			@Override
			public void responseError(VolleyError error) {

				RequestParams.convertError(context, error, true);

			}
		};

		requestUtil.getRechargeParams71();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recharge_btn_ok:
			// if (Double.valueOf(et_money.getText().toString()) < 20.00) {
			// MyToast.getToast(context, "充值金额不能低于20.00元").show();
			// et_money.setText("20.00");
			// return;
			// }
			// MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(
			// RechargeActivity.this);
			// boolean isMobile_spExist = mspHelper.detectMobile_sp();
			// if (!isMobile_spExist)
			// return;
			if (check()) {
				myAsynTask = new MyAsynTask(context, "正在支付...");
				myAsynTask.execute();
			}
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}

	public boolean check() {
		String text = et_money.getText() + "";
		boolean isPass = true;
		if (!"".equals(text)) {
			text = text + ".0";
			double money_text = Double.parseDouble(text);
			if (money_text < 20) {
				et_money.setText(20 + "");
				money = 20;
				MyToast.getToast(RechargeActivity.this, "至少充值20元").show();
				isPass = false;
			} else if (money_text > 100000) {// 输入金额大于可用余额
				et_money.setText(100000 + "");
				money = 100000;
				MyToast.getToast(RechargeActivity.this, "单笔充值金额最多100000元")
						.show();
				isPass = false;
			}
			setCursorPosition(et_money);
			money = money_text;
		} else {

			return false;
		}
		return isPass;
	}

	/** 文本框 监听 */
	private TextWatcher watcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
			String text = s.toString();
			if ("".equals(text)) {
				money = 20;
			}
			// double money_text=Double.parseDouble(text);
			// if(!"".equals(text)&&text.contains(".")){
			// String before_point=text.split("\\.")[0];
			// if(1!=text.split("\\.").length){
			// String point=text.split("\\.")[1];
			// int after_point=Integer.parseInt(point);
			// if(0!=after_point){
			// et_money.setText(before_point+".00");
			// money =Double.parseDouble(before_point+".00");
			// MyToast.getToast(RechargeActivity.this,"充值金额只能为整数").show();
			// return;
			// }
			// }
			// }
			// if(money_text<20){
			// et_money.setText("20.00");
			// money = Double.parseDouble(et_money.getText().toString());
			// MyToast.getToast(RechargeActivity.this,"至少充值20元").show();
			// return;
			// }else if(money_text>100000){//输入金额大于可用余额
			// et_money.setText(100000.00+"");
			// money =100000d;
			// MyToast.getToast(RechargeActivity.this,"单笔充值金额最多100000元").show();
			// return;
			// }
			// setCursorPosition(et_money);
			// money = Double.parseDouble(et_money.getText().toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}
	};

	private void setCursorPosition(EditText et_money) {
		CharSequence text = et_money.getText();
		if (text != null) {
			Selection.setSelection((Spannable) text, text.length());
		}
	}

	/** get the sign type we use. 获取签名方式 */
	private String getSignType() {
		return "sign_type=" + "\"" + "RSA" + "\"";
	}

	/** 关闭进度框 */
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// the handler use to receive the pay result.
	// 这里接收支付结果，支付宝手机端同步通知
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;
				Log.e("x", "strRet===" + strRet);
				switch (msg.what) {
				case App.RQF_PAY: {
					//
					closeProgress();
					BaseHelper.log("s", strRet);
					// 处理交易结果
					try {
						// 获取交易状态码，具体状态代码请参看文档
						String tradeStatus = "resultStatus={";
						int imemoStart = strRet.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = strRet.indexOf("};memo=");
						tradeStatus = strRet.substring(imemoStart, imemoEnd);
						// 先验签通知
						ResultChecker resultChecker = new ResultChecker(strRet);
						int retVal = resultChecker.checkSign();
						// 验签失败
						// if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED)
						// {
						// BaseHelper.showDialog(
						// RechargeActivity.this,
						// "提示",
						// getResources().getString(
						// R.string.check_sign_failed),
						// android.R.drawable.ic_dialog_alert);
						// } else {// 验签成功。验签成功后再判断交易状态码
						if (tradeStatus.equals("9000"))// 判断交易状态码，只有9000表示交易成功
						{ // ----------------huanghao
							// MyAsyn myAsyn = new MyAsyn();
							// myAsyn.execute(); //异步读取修改金额。
							// BaseHelper.showDialog(RechargeActivity.this,
							// "提示", "支付成功。交易状态码：" + tradeStatus,
							// R.drawable.infoicon);
							MyToast.getToast(context, "充值成功").show();
							double a1 = Double.parseDouble(App.user
									.getBalance());
							App.user.setBalance(a1
									+ Double.parseDouble(et_money.getText()
											.toString()));
							RechargeActivity.this.finish();
							Intent intent = new Intent(getApplicationContext(),
									MainActivity.class);
							RechargeActivity.this.startActivity(intent);
							MainActivity.toCenter();
						} else if (tradeStatus.equals("6001")) {
							MyToast.getToast(context, "用户取消支付").show();
						} else
							MyToast.getToast(context,
									"支付失败。交易状态码：" + tradeStatus).show();
						// BaseHelper.showDialog(RechargeActivity.this,
						// "提示", "支付失败。交易状态码：" + tradeStatus,
						// R.drawable.infoicon);

						// }

					} catch (Exception e) {
						e.printStackTrace();
						BaseHelper.showDialog(RechargeActivity.this, "提示",
								strRet, R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/* 发送请求查询充值后的余额*--------------huanghao */
	// class MyAsyn extends AsyncTask<Void, Integer, String>{
	//
	// @Override
	// protected String doInBackground(Void... params) {
	// opt = "41";
	// time = RspBodyBaseBean.getTime();
	// imei = RspBodyBaseBean.getIMEI(RechargeActivity.this);
	// info = "{}";
	// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
	// crc = RspBodyBaseBean.getCrc(time, imei, key, info,
	// App.user.getUid());
	// auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
	// String[] values = { opt, auth, info };
	// String result = HttpUtils.doPost(App.names, values,App.path);
	/* 以一定格式发送查询 返回result */
	// try {
	// JSONObject object = new JSONObject(result);
	// String isBinded = object.optString("isBinded");
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	// App.user.setBalance(10000);//设置新余额。
	// return "OK";
	// }
	// @Override
	// protected void onPostExecute(String result) {
	// super.onPostExecute(result);
	// if(result=="OK"){
	// myHandler.sendEmptyMessage(11);
	// }
	//
	//
	// }
	// }
	/** 拿到传到支付宝的数据 */
	private String getOrderInfo() {
		String[] names = { "uid", "payMoney" };
		String uid = App.user.getUid();

		// String payMoney = "0.01";

		if (et_money.getText().length() == 0)
			money = 1.00;
		else
			money = Double.parseDouble(et_money.getText().toString());

		String values[] = { uid, money + "" };

		String result = HttpUtils.doPost(names, values, App.zPath);

		System.out.println("支付宝---" + result);

		String strOrderInfo = "";

		String content = "";

		String sign = "";
		try {
			strOrderInfo = URLDecoder.decode(result, "UTF-8");
			System.out.println("解码后：" + strOrderInfo);

			content = strOrderInfo.substring(
					strOrderInfo.lastIndexOf("<content>") + 9,
					strOrderInfo.lastIndexOf("</content>"));
			sign = strOrderInfo.substring(
					strOrderInfo.lastIndexOf("<sign>") + 6,
					strOrderInfo.lastIndexOf("</sign>"));
			System.out.println("截取的" + content + "==" + sign);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("错误" + e.getMessage());
			return null;
		}

		sign = URLEncoder.encode(sign);
		strOrderInfo = content + "&sign=" + "\"" + sign + "\"" + "&"
				+ getSignType();
		// 对签名进行编码

		Log.i("x", "sign=1111=====  " + sign);

		Log.i("x", "拿到订单信息：" + strOrderInfo);
		return strOrderInfo;
	}

	// 06-24 16:02:13.750: I/System.out(316): 拿到订单信息：&sign=""sign_type="RSA"

	/*** 异步任务 用来后台获取数据 */
	class MyAsynTask extends MyAsynTaskWithProgress {
		/** 在后台执行的程序 */
		String error = "-1001";

		/**
		 * @param context
		 *            上下文
		 * @param title
		 *            进度框显示文字
		 */
		public MyAsynTask(Context context, String title) {
			super(context, title);
		}

		@Override
		protected String doInBackground(Integer... params) {
			try {
				// prepare the order info.
				// 准备订单信息
				String orderInfo = getOrderInfo();
				if (null == orderInfo)
					return null;
				// 调用pay方法进行支付
				// 构造PayTask 对象
//				PayTask alipay = new PayTask(RechargeActivity.this);
//				// 调用支付接口，获取支付结果
//				Log.i(TAG, "payInfo---->" + orderInfo);
//				String result = alipay.pay(orderInfo);

//				Message msg = new Message();
//				msg.what = SDK_PAY_FLAG;
//				msg.obj = result;
//				mHandler.sendMessage(msg);

				// MobileSecurePayer msp = new MobileSecurePayer();
				//
				// boolean bRet = msp.pay(orderInfo, mHandler, App.RQF_PAY,
				// RechargeActivity.this);
				//
				// Log.i("x", "bRet====" + bRet);
				// if (bRet) {
				// // show the progress bar to indicate that we have started
				// // paying.
				// // 显示“正在支付”进度条
				// myHandler.sendEmptyMessage(1);
				// } else
				// ;
			} catch (Exception ex) {
				Log.i("x", "充值出错---" + ex.getMessage());
			}
			return null;
		}
	}

	/** 处理页面显示的 */
	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -500:
				MyToast.getToast(RechargeActivity.this, "连接超时").show();
				break;
			case 1:
				closeProgress();
				mProgress = BaseHelper.showProgress(RechargeActivity.this,
						null, "正在支付", false, true);
				break;
			default:
				break;
			}
			if (myAsynTask != null
					&& myAsynTask.getStatus() == AsyncTask.Status.RUNNING) {
				myAsynTask.cancel(true); // 如果Task还在运行，则先取消它
			}
			super.handleMessage(msg);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		try {
			MyToast.getToast(RechargeActivity.this, "充值成功，跳转页面").show();
		} catch (Exception e) {
			Log.i("x", "--错误--" + e.getMessage());
		}
		super.onNewIntent(intent);
	}

}
